// CSE571 - dealer.cpp
// Authors: Jonathan Wald, Daniel Sarfati, Guangle Fan
// Dealer class which holds data about games and players for server.

#include <iostream>
#include "stdio.h"
#include <map>
#include <iterator>
#include <utility>

#include "dealer.h"
#include "player.h"
#include "signal-handler.h"

Dealer* Dealer::instance_ = NULL;

Dealer* Dealer::instance() {
  if (instance_ == NULL) {
    instance_ = new Dealer();
  }
  return instance_;
}

Dealer::Dealer() : plays_holdem(true),
                             plays_stud(true),
                             plays_draw(true) {}

// Service methods                                               
int Dealer::init (int argc, char *argv[]) {
  if(argc != 1) {
    std::cout << "Expecting 1 filename for client (re)initializa\
tion." << std::endl;
    return -1;
  }
  plays_draw = false;
  plays_holdem = false;
  plays_stud = false;
  ifstream file;
  file.open(argv[0]);
  if (!file.is_open()) { return -1; }
  while(file.good()) {
    string game_type;
    file >> game_type;
    if (game_type == "draw") {
      plays_draw = true;
    } else if (game_type == "holdem") {
      plays_holdem = true;
    } else if (game_type == "stud") {
      plays_stud = true;
    } else {
      std::cout << "Unrecognized game type " << game_type 
		<< " in defs file, continuing on." << std::endl;
    }
  }
  return 0;
}

int Dealer::fini (void) {
  return 0;
}

int Dealer::suspend (void) {
  map<string, Game *>::iterator giter;
  for (giter = games.begin(); giter != games.end(); ++giter) {
    giter->second->suspend();
  }
  for (giter = finished_games.begin(); giter != finished_games.end(); ++giter) {
    giter->second->suspend();
  }
  return 0;
}

int Dealer::resume (void) {
  map<string, Game *>::iterator giter;
  for (giter = games.begin(); giter != games.end(); ++giter) {
    giter->second->resume();
  }
  for (giter = finished_games.begin(); giter != finished_games.end(); ++giter) {
      giter->second->resume();
  }
  return 0;
}

int Dealer::info (char **, size_t) {
  std::cout << "Games supported by server: "
            << (plays_stud ? "Stud " : "")
            << (plays_draw ? "Draw " : "")
            << (plays_holdem ? "Holdem " : "")
            << std::endl;
  map<string, Game *>::iterator giter;
  for (giter = games.begin(); giter != games.end(); ++giter) {
      giter->second->info(NULL);
  }
 for (giter = finished_games.begin(); giter != finished_games.end(); ++giter) {
   giter->second->info(NULL);
  }
  return 0;
}

